/*
 * @Author: Marte
 * @Date:   2016-10-24 11:17:27
 * @Last Modified by:   Marte
 * @Last Modified time: 2016-10-26 10:46:24
 */

'use strict';

var _ = require('underscore');

module.exports = function(sequelize, DataTypes) {
    var PicTypeRemarkGroup = sequelize.define('PicTypeRemarkGroup', {

    }, {
        charset: 'utf8',
        classMethods: {
            associate: function(models) {
                PicTypeRemarkGroup.belongsTo(models.Type, {
                    constraints: false
                });
                PicTypeRemarkGroup.belongsTo(models.Remark, {
                    constraints: false
                });
                PicTypeRemarkGroup.belongsTo(models.RemarkGroup, {
                    constraints: false
                });
                PicTypeRemarkGroup.belongsTo(models.Pic, {
                    constraints: false
                });
            },
            fetch: function(op) {
                return this
                    .findAll(_.extend({
                        order: [
                            'createdAt'
                        ],
                        raw: true
                    }, op || {}));
            },
            findJsonByTypeAndRemark: function(typeId, remarkId, op) {
                var self = this;
                return self.findAll(_.extend({
                        where: {
                            TypeId: typeId,
                            RemarkId: remarkId
                        },
                        attributes: ['TypeId', 'RemarkId', 'RemarkGroupId', 'PicId'],
                        include: [{
                            association: self.associations.Pic,
                            attributes: ['fileName','fileFullName','origName']
                        }, {
                            association: self.associations.Type,
                            attributes: ['typeName']
                        }, {
                            association: self.associations.Remark,
                            attributes: ['remark']
                        }, {
                            association: self.associations.RemarkGroup,
                            attributes: ['groupName']
                        }]
                    }, op || {}))
                    .then(function(result) {
                        var picTRG=[];
                        _.each(result, function(item,i) {
                            //console.log(item);
                            picTRG.push(item.get({
                                plain: true
                            }));
                        });
                        return picTRG;
                    });
            }
        }
    });
    return PicTypeRemarkGroup;
};
